package com.wangchao.administrator.zenmechi.ui.searchactivity;

import android.content.Context;

import com.j256.ormlite.dao.Dao;
import com.wangchao.administrator.zenmechi.bean.caipudetailbean.CaipuDetail;
import com.wangchao.administrator.zenmechi.bean.merchantbean.MerchantBean;
import com.wangchao.administrator.zenmechi.bean.productbean.ProductBean;
import com.wangchao.administrator.zenmechi.db.SearchHistory;
import com.wangchao.administrator.zenmechi.db.SearchHistoryDbHelper;
import com.wangchao.administrator.zenmechi.http.HttpHelper;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2016/10/18.
 */
public class SearchActivityModel implements SearchActivityContract.Model {

    private List<SearchHistory> list;

    @Override
    public void searchHistory(Subscriber<List<SearchHistory>> subscriber, final Context context) {
        Observable.create(new Observable.OnSubscribe<List<SearchHistory>>() {
            @Override
            public void call(Subscriber<? super List<SearchHistory>> subscriber) {
                SearchHistoryDbHelper helper = SearchHistoryDbHelper.getInstance(context);
                Dao<SearchHistory,Long> HistoryDao = helper.getHistoryDao();
                try {
                    list = HistoryDao.queryForAll();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                subscriber.onNext(list);
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber);
    }

    @Override
    public void searchForCaipu(Map<String, String> map, Subscriber<CaipuDetail> subscriber) {
        //Log.i("tag","----------"+map.toString());
        HttpHelper.getInstance().getCaipuSearch(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber);
    }

    @Override
    public void searchForProduct(Map<String, String> map, Subscriber<ProductBean> subscriber) {
        //Log.i("tag","----------"+map.toString());
        HttpHelper.getInstance().getProductSearch(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber);
    }

    @Override
    public void searchMerchant(Map<String, String> map, Subscriber<MerchantBean> subscriber) {
        //Log.i("tag","----------"+map.toString());
        HttpHelper.getInstance().getMerchantSearch(map)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(subscriber);
    }
}
